import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../../../toolkit/utils/encrypt_utils.dart';
import '../../../constants.dart';
import '../../../services/api_service.dart';

class ResetPasswordLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final mmkv = MMKV.defaultMMKV();

  var obscureNewPassword = true.obs;
  var obscureConfirmPassword = true.obs;

  final formKey = GlobalKey<FormState>();
  final newPasswordController = TextEditingController();
  final confirmPasswordController = TextEditingController();

  var token = '';

  @override
  void onInit() {
    super.onInit();
    token = Get.arguments;
  }

  void onSubmit() async {
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();

      if (token.isEmpty) {
        EasyLoading.showError('请重新获取短信验证码！');
        Get.back();
        return;
      }

      EasyLoading.show(status: '正在修改密码...');

      var key = await apiService.getPayKey();
      if (key.isBlank ?? true) {
        EasyLoading.showError('获取密钥失败');
        return;
      }

      var newPassword = rsaEncrypt(key!, newPasswordController.text);

      var result = await apiService.changePassword(newPassword, token: token);
      EasyLoading.dismiss();
      if (result == null) {
        EasyLoading.showError('网络错误，请稍后重试！');
        return;
      }
      if (result.value['success'] == true) {
        _logout();
        Get.snackbar('密码修改成功', '请重新登录');
        Get.offAllNamed(RouteGet.login);
      } else {
        EasyLoading.showError(result.value['error']['message']);
      }
    }
  }

  void _logout() {
    mmkv.encodeString(kKeyToken, '');
    mmkv.encodeString(kKeyOrgId, '');
  }
}
